package com.john.market.activities;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import com.john.market.R;
import com.john.market.classes.Product;
import com.john.market.constants.BundleKeys;
import com.john.market.constants.ProductType;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.Spinner;
import android.widget.Toast;

/**
 * Activity for adding or updating a product
 * 
 */
public class FormActivity extends Activity {
	// Product ID
	private UUID mId = UUID.randomUUID();
	
	// Display mode
	private boolean mForEdit = false;
	
	/**
	 * Loads data to the view
	 *  
	 */
	private void loadBundle () {
		// Obtaining an intent data
		Bundle data = getIntent().getExtras();
		if (null == data) return;
		
		EditText editTitle = (EditText)findViewById(R.id.title);
				
		// Receiving display mode
		this.mForEdit = data.getBoolean(BundleKeys.KEY_FOR_EDIT);
		if (!this.mForEdit) {
			((Button)findViewById(R.id.request)).setText("Add");
			editTitle.requestFocus();
			return;
		}
		
		// Setting product ID
		mId = UUID.fromString(data.getString(BundleKeys.KEY_ID));
		 
		// Setting title of the product
		String title = data.getString(BundleKeys.KEY_TITLE);
		editTitle.setEnabled(false);
		editTitle.setText(title);
				
		// Setting type of the product
		int ordinal = data.getInt(BundleKeys.KEY_TYPE);
		Spinner spinner = (Spinner)findViewById(R.id.spinner);
		spinner.setSelection(ordinal);
		spinner.setEnabled(false);
		
		// Setting amount of the product
		String amount = data.getString(BundleKeys.KEY_AMOUNT);
		EditText editAmount = (EditText)findViewById(R.id.amount);
		editAmount.setText(amount);
		editAmount.requestFocus();
				
		// Setting price of the product
		String price = data.getString(BundleKeys.KEY_PRICE);
		((EditText)findViewById(R.id.price)).setText(price);
		 
		((Button)findViewById(R.id.request)).setText("Update");
		
		// Display hint
		String hint = "To remove, clear amount or put 0";
		Toast.makeText(this, hint, Toast.LENGTH_LONG).show();
		
	}
	
	/**
	 * Returns the data of entered by the user
	 * 
	 * @return The resulting {@link Product} object
	 * 
	 */
	private Product getProduct() {
		String value;
		
		// Getting title of the product
		String title = ((EditText)findViewById(R.id.title)).getText().toString();
		
		title.trim();
		if (title.length() == 0) {
			Toast.makeText(FormActivity.this, "Enter title of the product!", Toast.LENGTH_SHORT).show();
			return null;
		}
		
		// Getting type of the product
		int pos = ((Spinner)findViewById(R.id.spinner)).getSelectedItemPosition();
		ProductType type = ProductType.values()[pos];
		
		// Getting amount of the product
		int amount = 0;
		value = ((EditText)findViewById(R.id.amount)).getText().toString();
		
		if (value.length() != 0) {
			try {
				amount = Integer.parseInt(value);
			}
			catch (NumberFormatException e) {
				Toast.makeText(FormActivity.this, "Wrong number for amount!", Toast.LENGTH_SHORT).show();
				return null;
			}
		}
		else {
			amount = 0;
		}
		
		// Getting price of the product
		float price = 0;
		value = ((EditText)findViewById(R.id.price)).getText().toString();
		
		if (value.length() == 0) {
			Toast.makeText(FormActivity.this, "Enter price of the product!", Toast.LENGTH_SHORT).show();
			return null;
		}
		
		try {
			price = Float.parseFloat(value);
			if (price <= 0) {
				throw new NumberFormatException();
			}
			
			price = Math.round(price * 100.f) / 100.f;
		}
		catch (NumberFormatException e) {
			Toast.makeText(FormActivity.this, "Wrong number for price!", Toast.LENGTH_SHORT).show();
			return null;
		}
		
		// Creating a new product with received data
		Product product = new Product(title, type, amount, price);
		product.setId(this.mId);
		
		return product;
		
	}
	
	// Listener for the add/update button
	private OnClickListener mOnRequestListener = new OnClickListener() {
		@Override
		public void onClick(View view) {
			// Getting the data
			Product product = getProduct();
			if (product == null) {
				return;
			}
			
			// Setting response bundle
			Bundle bundle = new Bundle();
			bundle.putBoolean(BundleKeys.KEY_FOR_EDIT, mForEdit);
			bundle.putString(BundleKeys.KEY_ID, product.getId().toString());
			bundle.putString(BundleKeys.KEY_TITLE, product.getTitle());
			bundle.putInt(BundleKeys.KEY_TYPE, product.getType().ordinal());
			bundle.putInt(BundleKeys.KEY_AMOUNT, product.getAmount());
			bundle.putFloat(BundleKeys.KEY_PRICE, product.getPrice());
			
			// Creating intent for activity
			Intent intent = new Intent(FormActivity.this, FormActivity.class);
			intent.putExtras(bundle);
			
			// Close activity
			setResult(RESULT_OK, intent);
			finish();
			
		}
		
	};
	
	// Listener for the cancel button
	private OnClickListener mOnCancelListener = new OnClickListener() {
		@Override
		public void onClick(View view) {
			// Close activity
			setResult(RESULT_CANCELED, null);
			finish();
			
		}
		
	};
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.form);
        
        // Fill the product type spinner
        
        List<String> categories = new ArrayList<String>();
    	for (ProductType type : ProductType.values()) {
    		categories.add(type.toString());
    	}
    	
    	Spinner spinner = (Spinner)findViewById(R.id.spinner);
    	spinner.setAdapter(new ArrayAdapter<String>(this,
    				android.R.layout.simple_spinner_item,
    				categories));
        
    	// Set listeners for buttons
    	
    	Button request = (Button)findViewById(R.id.request);
        request.setOnClickListener(this.mOnRequestListener);
        
        Button cancel = (Button)findViewById(R.id.cancel);
        cancel.setOnClickListener(this.mOnCancelListener);
        
        // Load data
        loadBundle();
        
	}
	
}
